import { defineStore } from 'pinia';
import { getLeftData } from '@/api/earlyWarning';
import { RescueForces } from '@/constants/components/rescueForces';
import { mapBackendData, type moduleInfo } from '@/utils/mapBackendData';
import { getEmergencyRepair, getEmergencyRepairByType } from '@/api/rescueForces';
import { useCesiumPoints } from '@/hooks/useCesiumPoints';
import COMPONENT_TITLES from '@/constants/components/componentsTitle';
import { useDialogStore } from '@/store/modules/useDialogStore';

// 站点类型映射配置(中文名称与后端字段的映射关系)
const RESCUE_FORCES_MAPPING = {
  '防护目标': { countKey: 'protectiveEquipmentNum' },
  '抢救物品': { countKey: 'rescueItemsNum' },
  '气体检测仪': { countKey: 'gasDetectorNum' },
  '应急通讯设备': { countKey: 'communicationEquipmentNum' },
  '抢修工具': { countKey: 'repairToolsNum' },
  '预备动力设备': { countKey: 'expectedPowerEquipmentNum' }
} as const; // as const确保类型推断为字面量类型
export const useRescueForcesStore = defineStore('rescueForces', () => {
  const emergencyResourcesData = ref<moduleInfo[]>(RescueForces);
  const emergencyRepairTeamTotal = ref<number>(0);
  const dataSource = reactive<Record<string, any[]>>({});
  const { addPoint, clearAllPoints } = useCesiumPoints();
  const activeType = ref<string | null>(null); //记录唯一值
  const currentRepairTeamList = ref<any[]>([]); //用于弹窗 抢修队列表
  const { openDialog } = useDialogStore();
  const { flyTo } = useDialogStore();
  // 创建一个通用的点位切换处理器
  const createPointToggleHandler = (
    nameGenerator: (type?: number) => string,
    dataFetcher: (type?: number) => Promise<{
      data: any[];
    }>
  ) => {
    return async (type?: number) => {
      const name = nameGenerator(type);
      flyTo({ longitude: 117.140035075, latitude: 36.798747059 }, 400000);

      if (activeType.value === name) {
        clearAllPoints(dataSource[name]);
        activeType.value = null;
        return;
      }

      // 先取消当前显示的点位
      if (activeType.value) {
        clearAllPoints(dataSource[activeType.value]);
      }

      // 获取数据并添加点位
      const { data } = await dataFetcher(type);
      openDialog('repairTeamModule');
      currentRepairTeamList.value = data;
      dataSource[name] = data.map((point) => addPoint(point, COMPONENT_TITLES.REPAIR_TEAM));
      activeType.value = name;
    };
  };

  // 原始函数重构
  const emergencyRepairTeam = createPointToggleHandler(
    () => COMPONENT_TITLES.REPAIR_TEAM,
    () => getEmergencyRepair()
  );

  const deviceHandler = createPointToggleHandler(
    (type) => COMPONENT_TITLES.REPAIR_TEAM + type,
    (type) => getEmergencyRepairByType({ type })
  );
  //初始化救援队点位
  const initRescueForces = () => {
    for (const key in dataSource) {
      clearAllPoints(dataSource[key]);
    }
  };

  // 初始化应急资源数据
  const initEmergencyResources = async () => {
    const { data } = await getLeftData({ type: 'emergencyResources' });
    emergencyResourcesData.value = mapBackendData(RescueForces, data.emergencyResources, RESCUE_FORCES_MAPPING);
    emergencyRepairTeamTotal.value = data.emergencyResources.emergencyRepairTeam.length;
  };

  return {
    emergencyResourcesData,
    emergencyRepairTeamTotal,
    emergencyRepairTeam,
    deviceHandler,
    currentRepairTeamList,
    initRescueForces,
    initEmergencyResources
  };
});
